//========================================================================================
//  
//  $File: $
//  
//  Owner: Toan Nguyen
//  
//  $Author: $
//  
//  $DateTime: $
//  
//  $Revision: $
//  
//  $Change: $
//  
//  Copyright 1997-2008 Adobe Systems Incorporated. All rights reserved.
//  
//  NOTICE:  Adobe permits you to use, modify, and distribute this file in accordance 
//  with the terms of the Adobe license agreement accompanying it.  If you have received
//  this file from a source other than Adobe, then your use, modification, or 
//  distribution of it requires the prior written permission of Adobe.
//  
//========================================================================================

#include "VCPlugInHeaders.h"

// Implementation includes
#include "widgetid.h"

// Interface includes
#include "ISubject.h"
#include "IControlView.h"
#include "ITreeViewController.h"
#include "IApplication.h"
#include "IDialogMgr.h"

// General includes:
#include "CoreResTypes.h"
#include "LocaleSetting.h"
#include "RsrcSpec.h"

// Implem includes
#include "AMPCAlert.h"
#include "CObserver.h"
#include "K2Vector.tpp" // For NodeIDList to compile
#include "AMPNodeID.h"
#include "AMPID.h"
#include "SDKLayoutHelper.h"
#include "HTTPRequestHelper.h"
#include "JSONHelper.h"
#include "AMGlobal.h"
#include "AMPDocument.h"
#include "AMPLogDataRecord.h"
#include "ITextControlData.h"
#include "IWidgetParent.h"
#include "IPalettePanelUtils.h"
#include "IPanelControlData.h"
#include "SDKFileHelper.h"
#include "K2Vector.tpp" // For NodeIDList to compile
#include "StreamUtil.h"
#include "ISysFileData.h"
#include "ITriStateControlData.h"
#include "AMPLogCenter.h"

/**

	Observes the listbox via IID_ITREEVIEWCONTROLLER.
	
*/

class AMPListBoxObserver : public CObserver
{
public:
	
	/**
		@param interface ptr from boss object on which this interface is aggregated.
	*/
	AMPListBoxObserver(IPMUnknown *boss);

	/**
		Destructor for AMPListBoxObserver class
		
	*/	
	~AMPListBoxObserver();

	/**
		AutoAttach is only called for registered observers
		of widgets.  This method is called by the application
		core when the widget is shown.
	
	*/	
	virtual void AutoAttach();

	/**
		AutoDetach is only called for registered observers
		of widgets. Called when widget hidden.
	*/	
	virtual void AutoDetach();

	/**
		This class is interested in changes along IID_ILISTCONTROLDATA protocol with classID of
		kListSelectionChangedMessage. This message is sent when a user clicks on an element
		in the list-box.

	
		@param theChange this is specified by the agent of change; it can be the class ID of the agent,
		or it may be some specialised message ID.
		@param theSubject this provides a reference to the object which has changed; in this case, the button
		widget boss object that is being observed.
		@param protocol the protocol along which the change occurred.
		@param changedBy this can be used to provide additional information about the change or a reference
		to the boss object that caused the change.
	*/	
	virtual void Update(const ClassID& theChange, ISubject* theSubject, const PMIID &protocol, void* changedBy);
	
	//RangeProgressBar *ProgressBar;
	//int32			  ProgressCount;
	void BrowseIssueRefresh();
	
	IDialog* DoOpenDialog(int32 nTypeDialog, bool CloseDlg = TRUE);
	
	int updatePackageSession();
	
	int updateStorySession();
};

CREATE_PMINTERFACE(AMPListBoxObserver, kAMPListBoxObserverImpl)

AMPListBoxObserver::AMPListBoxObserver(IPMUnknown* boss)
: CObserver(boss)
{
	//printf("AMPListBoxObserver::AMPListBoxObserver \n");
}


AMPListBoxObserver::~AMPListBoxObserver()
{
	
}

/********************************************************************************************************************
 *****Function: AutoAttach
 *****Creator:  Toan Nguyen
 *****IN: 
 *****out: 
 *****Objective: 
 ********************************************************************************************************************/
void AMPListBoxObserver::AutoAttach()
{
	InterfacePtr<ISubject> subject(this, UseDefaultIID());
	if (subject != nil)
	{
		subject->AttachObserver(this, IID_ITREEVIEWCONTROLLER);
	}
}

/********************************************************************************************************************
 *****Function: AutoDetach
 *****Creator:  Toan Nguyen
 *****IN: 
 *****out: 
 *****Objective: 
 ********************************************************************************************************************/
void AMPListBoxObserver::AutoDetach()
{
	InterfacePtr<ISubject> subject(this, UseDefaultIID());
	if (subject != nil)
	{
		//subject->DetachObserver(this, IID_ITREEVIEWCONTROLLER);
	}
}

/********************************************************************************************************************
 *****Function: Update
 *****Creator:  Toan Nguyen
 *****IN: 
 *****out: 
 *****Objective: 
 ********************************************************************************************************************/
void AMPListBoxObserver::Update
(
	const ClassID& theChange, 
	ISubject* theSubject, 
	const PMIID &protocol, 
	void* changedBy
)
{
	////cout << "AMPListBoxObserver::Update" << endl;
	if ((protocol == IID_ITREEVIEWCONTROLLER) && (theChange == kListSelectionChangedMessage) ) {
		do {
			InterfacePtr<ITreeViewController> 	controller(this, UseDefaultIID());
			ASSERT(controller);
			if(!controller)
			{
				break;
			}
			PMString item;
			//bool16   casesensitive;
			NodeIDList selectedItems;
			controller->GetSelectedItems(selectedItems);

			const int kSelectionLength =  selectedItems.size() ;
			if (kSelectionLength> 0 )
			{
				PMString dbgInfoString("Selected item(s): ");
				string HelloUser = "Sign out (" + g_Username + ")" ;
				PMString kAMPluginSignOut(HelloUser.c_str());
				K2Vector<NodeID>::const_iterator iter, startIter, endIter;
				startIter = selectedItems.begin();
				endIter = selectedItems.end();
				for(iter = startIter; iter != endIter; ++iter)
				{
					const AMPNodeID* oneNode = static_cast<const AMPNodeID*>(iter->Get());
					item = oneNode->GetName();
					item.Translate();
					dbgInfoString.Append(item);
					dbgInfoString += ", ";
				}
				if (item == kAMPluginSignInStr)
				{
					DoOpenDialog(AMPluginCMSLoginAction);
					//AMPUtils::TestIconFrame();
				}
				//else if (item == kAMPluginSignOutStr) {
				else if ((item == kAMPluginSignOut && g_DocName.length() == 0) ||
						 (item == kAMPluginSignOut && g_DocName.length() > 0 && g_DocName.compare(AMPUtils::FrontDocName()) != 0)) {
					// sign out immediately and keep log info
					// AMPUtils::CloseCurDocument();	//added to close document 20121016
					bool FindDocsWork = AMPUtils::FindFrontDocsName(g_DocName.c_str());
					if (FindDocsWork == FALSE) {
						AMPUtils::ClearPackageAndSessionInfo();
						AMPUtils::ClearUserInfo();
						AMPUtils::RefreshMainPanel(FALSE);
						BrowseIssueRefresh();
						break;
					}else {
						AMPUtils::CheckinWhenLogout();
						if(Utils<ISelectionUtils>() != nil) {
							InterfacePtr<ISelectionManager> selectionManager(Utils<ISelectionUtils>()->QueryActiveSelection());
							selectionManager->DeselectAll(nil);
						}
						BrowseIssueRefresh();
						// check in existing file
					}
				}
				else if (item == kAMPluginSignOut && g_DocName.length() > 0 && g_DocName.compare(AMPUtils::FrontDocName()) == 0) {

					InterfacePtr<ISelectionManager> selectionManager(Utils<ISelectionUtils>()->QueryActiveSelection());
					int update = updatePackageSession();
					if(update != TRUE)
					{
						controller->DeselectAll();
						if(selectionManager != nil)
							selectionManager->DeselectAll(nil);
						break;
					}
					PMString alertStr("\nBefore you sign-out, would you like to check-in and save changes?");
					int16 result = AMPCAlert::ModalAlert
					(
					 //PMString("Do you want to sign out from CMS? Please check in your change"),		// Alert string
					 alertStr,
					 PMString("Check-in"),					// YES
					 PMString("Discard"), 					// NO
					 kCancelString,					// CANCEL
					 kNeedToWaitForDialog,							// Set kNeedToWaitForDialog to default
					 1							// No icon.
					 );
					////cout << "button selected: " << result << endl;
					
					if (result == kOKSystem) // YES
					{
						////cout << "Yes selected" << endl;
						// check in locked text frames
						bool idmlCheckinSuccess = FALSE;
						//bool storiesCheckinSuccess = FALSE;
						//storiesCheckinSuccess = AMPUtils::CheckInAllStories();
						
						// deselect text frame
						if(Utils<ISelectionUtils>() != nil) {
							//InterfacePtr<ISelectionManager> selectionManager(Utils<ISelectionUtils>()->QueryActiveSelection());
							selectionManager->DeselectAll(nil);
						}
						bool shouldPost = TRUE;
						//shouldPost = AMPUtils::SetIDToTextFrame();
						if (shouldPost == TRUE) {
							idmlCheckinSuccess = AMPDocument::DocumentControl();
							
						}
						else {
							// display error
							//isSuccessful = FALSE;
						}
						
						if (/*storiesCheckinSuccess == TRUE && */idmlCheckinSuccess == TRUE) {
							// Reset variables
							AMPUtils::ClearAllFile();
							AMPUtils::CloseCurDocument();	//added to close document 20121016
						}
						else {
							AMPCAlert::ModalAlert
							(
							 PMString("\nLogin Failed.\n\nPlease login to check-in your changes."),	// Alert string
							 kOKString, 					// OK button
							 kNullString, 					// No second button
							 kNullString, 					// No third button
							 kNoNeedToWaitForDialog,		// Set OK button to default
							 1								// No icon.
							 );
						}
						AMPUtils::CloseCurDocument();	//added to close document 20121016
						AMPUtils::ClearPackageAndSessionInfo();
						//ResetGlobalValue();
						AMPUtils::ClearUserInfo();
						AMPUtils::RefreshMainPanel(FALSE);
						
					}
					else if (result == kCancelSystem) // NO
					{
						////cout << "No selected" << endl;
						// unlock package and stories
						bool res = FALSE;
						res = AMPUtils::UnlockStories();
						if (res == FALSE) {
							// add to action queue
						}
						res = AMPUtils::UnlockPackage();
						AMPUtils::CloseCurDocument();	//added to close document 20121016
						if (res == FALSE) {
							// add to action queue
						}
						else {
							// Clean up
							AMPUtils::ClearAllFile();
							AMPUtils::ClearPackageAndSessionInfo();
							AMPUtils::ClearUserInfo();
							AMPUtils::RefreshMainPanel(FALSE);
							
						}
						
					}
					else { // CANCEL
						// do nothing
						////cout << "cancel selected" << endl;
					}
					BrowseIssueRefresh();
				}				
				else if (item == kAMPluginBrowseIssueStr && g_IsLoggedIn == TRUE)
				{
					string _error_info;
					PMString str("Loading issues list...");
					RangeProgressBar * BrowseProgress;
					BrowseProgress = new RangeProgressBar(str, 0, 200, kTrue, kFalse, nil, kFalse);
					
					string deleteLink = "rm -rf " + g_System_WorkspaceDir + "/*.jpg";
					system(deleteLink.c_str());
					string api_prefix = API_PREFIX;
					////cout << "url to get issue list " << g_Domain + api_prefix+"/magazines" << endl;
					
					string content = HTTPRequestHelper::getDataFromURL(g_Domain + "/" + api_prefix + "/magazines");
					BrowseProgress->SetPosition(15);
					if(content == "Error Code")
					{
						//CAlert::InformationAlert("Internal Server Error. Please try to connect again!");
						AMPCAlert::ModalAlert
						(
						 "\nInternal Server Error\n\nPlease try again later.",	// Alert string
						 kOKString, 					// OK button
						 kNullString, 					// No second button
						 kNullString, 					// No third button
						 kNoNeedToWaitForDialog,		// Set OK button to default
						 1								// No icon.
						 );
						controller->DeselectAll();
						BrowseProgress->~RangeProgressBar();
						break;
					}
					////cout << "content: " << content << endl;
					JSONHelper::initMagazines(content);
					BrowseProgress->SetPosition(20);
					int fraction = 160;
					if (g_Magazine_Count != 0) {
						fraction = fraction / g_Magazine_Count;
					}
					////cout << "fraction " << fraction << endl;
					for (int i = 0; i < g_Magazine_Count; i++) {
						BrowseProgress->SetPosition(25 + i*fraction);
						string issueURL = g_Domain + "/" + api_prefix + "/magazines/" + g_Magazines[i]._id;
						//string issueURL = g_Domain + "/" + api_prefix + "/magazines_revise/" + g_Magazines[i]._id;
						string issueContent = HTTPRequestHelper::getDataFromURL(issueURL);
						
						////cout << "fillMagazine: " << issueContent << endl;
						JSONHelper::fillMagazine(i, issueContent, TRUE, 40 + i*fraction, 40 + (i+1)*fraction, BrowseProgress, TRUE);
						////cout << "end fillMagazine";
					}
					//g_IsIssueEnable = TRUE;
					BrowseProgress->~RangeProgressBar();
					delete BrowseProgress;
					
					bool shouldDisplayAlert = TRUE;
					for (int j = 0; j < g_Magazine_Count; j++) {
						////cout << "magazine j issue size: " << g_Magazines[j]._issueSize << endl;
						if (g_Magazines[j]._issueSize > 0) {
							DoOpenDialog(AMPluginBrowserIssueAction);	
							shouldDisplayAlert = FALSE;
							break;
						} 
					}
					
					if (shouldDisplayAlert == TRUE) {
						
						_error_info = "Server error, can't get issue list from CMS";
						SaveLogCenterData(_error_info);
						AMPLogCenter::DataLogCenter(AMPPLUGIN_SHOW_ISSUE_LIST_FAILED);
						AMPCAlert::ModalAlert
						(
						 "\n\nIssue unavailable. Please try again later.",	// Alert string
						 kOKString, 					// OK button
						 kNullString, 					// No second button
						 kNullString, 					// No third button
						 kNoNeedToWaitForDialog,		// Set OK button to default
						 1								// No icon.
						 );
					}
				}
				else if (item == kAMPluginCheckInStr && g_DocName.compare(AMPUtils::FrontDocName()) != 0) {
				//else if (item == kAMPluginCheckInStr && FALSE) {
					//CAlert::InformationAlert("You can't check in this page");
					
					AMPCAlert::ModalAlert
					(
					 "\n\nYou can't check this page in",	// Alert string
					 kOKString, 					// OK button
					 kNullString, 					// No second button
					 kNullString, 					// No third button
					 kNoNeedToWaitForDialog,		// Set OK button to default
					 1								// No icon.
					 );
					
				}
				else if (item == kAMPluginCheckInStr && g_DocName.compare(AMPUtils::FrontDocName()) == 0) {
					// Update session before check in package
					// deselect text frame
					if(Utils<ISelectionUtils>() == nil)
					{
						controller->DeselectAll();
						break;
					}
					InterfacePtr<ISelectionManager> selectionManager(Utils<ISelectionUtils>()->QueryActiveSelection());
					
					int update = updatePackageSession();
					if(update != TRUE)
					{
						controller->DeselectAll();
						if(selectionManager != nil)
							selectionManager->DeselectAll(nil);
						break;
					}
				//else if (item == kAMPluginCheckInStr) {
					int16 result = AMPCAlert::ModalAlert
											(
												PMString("\n\nWant to check-in?"),		// Alert string
												PMString("Check-in and close"),//kYesString,						// YES button	
												PMString("Check-in and continue"),//kNoString,						// NO button
												PMString("Cancel"),//kNullString, 					// No third button
												kNeedToWaitForDialog,								// Set kNeedToWaitForDialog to default
												kAMPLuginCheckInAction								// No icon.
											 );
					
					if (result == kOKSystem)		// check in and close
					{
						// check in locked text frames
						bool idmlCheckinSuccess = FALSE;
						//bool storiesCheckinSuccess = FALSE;
						//storiesCheckinSuccess = AMPUtils::CheckInAllStories();
						
						// deselect text frame
						//if(Utils<ISelectionUtils>() != nil)
						//{
						//	InterfacePtr<ISelectionManager> selectionManager(Utils<ISelectionUtils>()->QueryActiveSelection());
						//	selectionManager->DeselectAll(nil);
						//}
						if(!selectionManager)
							selectionManager->DeselectAll(nil);
						
						bool shouldPost = TRUE;
						//shouldPost = AMPUtils::SetIDToTextFrame();
						if (shouldPost == TRUE) {
							idmlCheckinSuccess = AMPDocument::DocumentControl();
							////cout << "idmlCheckinSuccess: " << idmlCheckinSuccess << endl;
						}
						else {
							// display error
							//isSuccessful = FALSE;
						}
						
						if (/*storiesCheckinSuccess == TRUE &&*/ idmlCheckinSuccess == TRUE) {
							AMPUtils::CloseCurDocument();
							
							//AMPUtils::ClearAllFile();
							AMPUtils::ResetLogFile();
							////cout << "clear all file " << endl;
							AMPUtils::ClearPackageAndSessionInfo();
							AMPUtils::RefreshMainPanel(FALSE);
							//BrowseIssueRefresh();
							AMPCAlert::ModalAlert
							(
							 PMString("\n\nCheck-in Successful"),	// Alert string
							 "OK", 							// Yes button
							 kNullString, 					// No button
							 kNullString, 					// No third button
							 kNoNeedToWaitForDialog,		// Set OK button to default
							 1								// No icon.
							 );
						}
						else {
							//AMPDocument::Relink();
							AMPUtils::RemoveIDFromTextFrames();
							// display error
							AMPCAlert::ModalAlert (
							PMString("Check-in Failed.\n\nPlease check your internet connection and try again."),		// Alert string
							PMString("OK"), 					// NO button
							kNullString,					// YES second button
							kNullString, 					// No third button
							kNoNeedToWaitForDialog,			// Set OK button to default
							1								// No icon.
							);	
							
						}
					}
					else if (result == 2)		// check in and continue
					{
						//cout << "check in and continue" << endl;
						//AMPUtils::SetStoryIDToTextFrame();
						//bool storiesCheckinSuccess = FALSE;
						bool idmlCheckinSuccess = FALSE;
						//storiesCheckinSuccess = AMPUtils::CheckInAllStories();
						
						if(!selectionManager)
							selectionManager->DeselectAll(nil);
						
						bool shouldPost = TRUE;
						if (shouldPost == TRUE) {
							idmlCheckinSuccess = AMPDocument::DocumentControl(TRUE);
						}
						
						//AMPDocument::Relink();
						AMPUtils::RemoveIDFromTextFrames();
						if (/*storiesCheckinSuccess == TRUE &&*/ idmlCheckinSuccess == TRUE) {
							AMPUtils::StoryInfoHiddenSetting();
							AMPCAlert::ModalAlert
							(
							 PMString("\n\nCheck-in Successful"),	// Alert string
							 kOKString, 					// Yes button
							 kNullString, 					// No button
							 kNullString, 					// No third button
							 kNoNeedToWaitForDialog,		// Set OK button to default
							 1								// No icon.
							 );
						}else {
							// display error
							AMPCAlert::ModalAlert (
												PMString("Check-in Failed.\n\nPlease check your internet connection and try again."),		// Alert string
												PMString("OK"), 					// NO button
												kNullString,					// YES second button
												kNullString, 					// No third button
												kNoNeedToWaitForDialog,			// Set OK button to default
												1								// No icon.
												);	
						}
						
					}
				}	
				else if (item == kAMPluginCheckInStoryStr && g_TextSelected == TRUE) {
					// Update session before check in package
					if(Utils<ISelectionUtils>() == nil)
					{
						controller->DeselectAll();
						break;
					}
					// deselect text frame
					InterfacePtr<ISelectionManager> selectionManager(Utils<ISelectionUtils>()->QueryActiveSelection());
					
					int update = updateStorySession();
					if(update != TRUE)
					{
						controller->DeselectAll();
						if(selectionManager != nil) {
							selectionManager->DeselectAll(nil);
						}
						break;
					}
					// check in immediately
					AMPUtils::PostStoryToCMS();
					// deselect text frame
					//InterfacePtr<ISelectionManager> _selectionManager(Utils<ISelectionUtils>()->QueryActiveSelection());
					if(selectionManager != nil) {
						selectionManager->DeselectAll(nil);
					}
				}	
				else if (item == kAMPluginCheckOutStoryStr && g_TextSelected == TRUE) {
				}
				else
				{
					// should do nothing
					//dbgInfoString.Truncate(2); //remove the last ', '
					//dbgInfoString.SetTranslatable(kFalse);	// only for debug- not real code
					//CAlert::InformationAlert(dbgInfoString);

				}
				controller->DeselectAll();
			}
		} while(0);
	}
}

/********************************************************************************************************************
 *****Function: DoOpenDialog
 *****Creator:  Toan Nguyen
 *****IN: int32 nTypeDialog, bool CloseDlg
 *****out: 
 *****Objective: open dialog
 ********************************************************************************************************************/
IDialog* AMPListBoxObserver::DoOpenDialog(int32 nTypeDialog, bool CloseDlg)
{

	do
	{
		int32	DialogResourceID;
		if (nTypeDialog == AMPluginCMSLoginAction)
		{
			DialogResourceID = kCMSLoginDialogResourceID;
		} 
		else if (nTypeDialog == AMPluginBrowserIssueAction)
		{
			DialogResourceID = kBscSlDlgIssuesDialogResourceID;
		}
		else if (nTypeDialog == kAMPStoryAssignmentAction)
		{
			DialogResourceID = kImgAssignmentDlgRsrcID;
		}
		else if (nTypeDialog == kAMPLuginProgressAction)
		{
			DialogResourceID = kAMPProgressDlgResourceID;
		}
		else if (nTypeDialog == kAMPFunctionProAction)
		{
			DialogResourceID = kAMPAFunctionProDlgResourceID;
		}

		// Get the application interface and the DialogMgr.	
		InterfacePtr<IApplication> application(GetExecutionContextSession()->QueryApplication());
		if (application == nil)
		{
			ASSERT_FAIL("BscDlgActionComponent::DoDialog: application invalid");
			break;
		}
		InterfacePtr<IDialogMgr> dialogMgr(application, UseDefaultIID());
		if (dialogMgr == nil)
		{ 
			ASSERT_FAIL("BscDlgActionComponent::DoDialog: dialogMgr invalid"); 
			break;
		}
		// Load the plug-in's resource.
		PMLocaleId nLocale = LocaleSetting::GetLocale();
		RsrcSpec dialogSpec
			(
			nLocale,					// Locale index from PMLocaleIDs.h. 
			kAMPPluginID,				// Our Plug-in ID from BasicDialogID.h. 
			kViewRsrcType,				// This is the kViewRsrcType.
			DialogResourceID,			// Resource ID for our dialog.
			kTrue						// Initially visible.
			);

		// CreateNewDialog takes the dialogSpec created above, and also
		// the type of dialog being created (kMovableModal).
		IDialog* dialog = dialogMgr->CreateNewDialog(dialogSpec, IDialog::kMovableModal);
		
		if (dialog == nil)
		{ 
			ASSERT_FAIL("BscDlgActionComponent::DoDialog: can't create dialog"); 
			break;
		}
		////cout << "Open the dialog." << endl;
		// Open the dialog.
		if(CloseDlg == TRUE) {
			dialog->Open();
		}else{
			dialog->Close();
		}
		
		return dialog;
		////cout << "Open the dialog finshed" << endl;
	} while (false);
	
	return NULL;

}

/********************************************************************************************************************
 *****Function: BrowseIssueRefresh
 *****Creator:  Toan Nguyen
 *****IN: 
 *****out: 
 *****Objective: refresh browse issue list
 ********************************************************************************************************************/
void AMPListBoxObserver::BrowseIssueRefresh()
{
	do
	{
		string displayString, SetDefaultPath;
		////cout << "BrowseIssueRefresh()" << endl;
		
		// Get the application interface and the DialogMgr.	
		InterfacePtr<IApplication> application(GetExecutionContextSession()->QueryApplication());
		if (application == nil)
		{
			////cout << "BscDlgActionComponent::DoDialog: application invalid" << endl;
			break;
		}
		InterfacePtr<IDialogMgr> dialogMgr(application, UseDefaultIID());
		if (dialogMgr == nil)
		{ 
			////cout << "BscDlgActionComponent::DoDialog: dialogMgr invalid" << endl;
			break;
		}
		// Load the plug-in's resource.
		PMLocaleId nLocale = LocaleSetting::GetLocale();
		RsrcSpec dialogSpec
		(
		 nLocale,					// Locale index from PMLocaleIDs.h. 
		 kAMPPluginID,				// Our Plug-in ID from BasicDialogID.h. 
		 kViewRsrcType,				// This is the kViewRsrcType.
		 kBscSlDlgIssuesDialogResourceID,			// Resource ID for our dialog.
		 kTrue						// Initially visible.
		 );
		
		// CreateNewDialog takes the dialogSpec created above, and also
		// the type of dialog being created (kMovableModal).
		IDialog* dialog = dialogMgr->CreateNewDialog(dialogSpec, IDialog::kMovableModal);
		if (dialog == nil)
		{ 
			//ASSERT_FAIL("BscDlgActionComponent::DoDialog: can't create dialog"); 
			break;
		}
	
		InterfacePtr<IPanelControlData> iPanelControlData(dialog, UseDefaultIID());
		ASSERT(iPanelControlData);
		if(iPanelControlData==nil) {
			////cout << "panelControlData invalid" << endl;
			break;
		}
		
		IControlView* iWidgetView = iPanelControlData->FindWidget(kAMPCheckOutButtonWidgetID);
		ASSERT(iWidgetView);
		if(!iWidgetView) {
			////cout << "error 2" << endl;
			break;
		}
		
		// Get Next and Previous buttons
		IControlView* nextButtonView = 
		iPanelControlData->FindWidget(kPreviewImageNextWidgetID);
		ASSERT(nextButtonView);
		if(!nextButtonView) {
			////cout << "error 3" << endl;
			break;
		}
		
		IControlView* prevButtonView = 
		iPanelControlData->FindWidget(kPreviewImagePreviousWidgetID);
		ASSERT(prevButtonView);
		if(!prevButtonView) {
			////cout << "error 4" << endl;
			break;
		}
		IControlView* radioButtonPanel = iPanelControlData->FindWidget(kAMPClusterPanelWidgetID);
		ASSERT(radioButtonPanel);
		if(!radioButtonPanel)
		{
			////cout << "error 5" << endl;
			break;
		}
		
		IControlView* RadioLowchildView = iPanelControlData->FindWidget(kBscRadioLowResWidgetID);
		if (RadioLowchildView == nil)
		{
			////cout << "error RadioLowchildView" << endl;
			break;
		}
		InterfacePtr<ITriStateControlData> triDataLow(RadioLowchildView, UseDefaultIID());
		if (triDataLow)
		{
			////cout << "error triData" << endl;
			triDataLow->SetState(ITriStateControlData::kSelected, nil, nil);
		}
		
		IControlView* RadioHighchildView = iPanelControlData->FindWidget(kBscRadioHighResWidgetID);
		if (RadioHighchildView == nil)
		{
			////cout << "error RadioLowchildView" << endl;
			break;
		}
		InterfacePtr<ITriStateControlData> triDataHigh(RadioHighchildView, UseDefaultIID());
		if (triDataHigh)
		{
			////cout << "error triDataHigh" << endl;
			triDataHigh->SetState(ITriStateControlData::kUnselected, nil, nil);
		}
		
		IControlView* textMessageWidget = iPanelControlData->FindWidget(kAMPIssuesTextMessageWidgetID);
		ASSERT(textMessageWidget);
		if(!textMessageWidget)
		{
			////cout << "error 6" << endl;
			break;
		}
		
		InterfacePtr<ITextControlData> textControlData(textMessageWidget, UseDefaultIID());
		ASSERT(textControlData);
		if(!textControlData)
		{
			////cout << "error 7" << endl;
			break;
		}
		IControlView* iPreviewMainView = iPanelControlData->FindWidget(kAMPGroupViewPanelWidgetID);
		ASSERT(iPreviewMainView);
		if(!iPreviewMainView) {
			break;
		}
		
		IControlView* iLeftRightView = iPanelControlData->FindWidget(kAMPGroupPanelWidgetID);
		ASSERT(iLeftRightView);
		if(!iLeftRightView) {
			break;
		}
		
		IControlView* iViewWidgetView = 
		iPanelControlData->FindWidget(kAMPCustomPanelViewWidgetID);
		ASSERT(iViewWidgetView);
		if(!iViewWidgetView) {
			//cout << "iViewWidgetView is nil" << endl;  
			break;
		}

		// setup init again for Browse Issue
		{
			iWidgetView->Disable(kTrue);
			nextButtonView->Disable(kTrue);
			prevButtonView->Disable(kTrue);
			radioButtonPanel->Disable(kTrue);
			displayString = "Preview";
			g_Resolution = "low";
			SetDefaultPath =  g_ImagePreview;
			
			textControlData->SetString(displayString.c_str());
			
			// display page preview at center
			iLeftRightView->Disable();
			iLeftRightView->Hide();
			
			iPreviewMainView->Enable(TRUE, TRUE);
			iPreviewMainView->Show();
			iViewWidgetView->Enable(TRUE, TRUE);
			iViewWidgetView->Show();
		}
		
		PMString path(SetDefaultPath.c_str());
		SDKFileHelper fileHelper(path);
		IDFile xFile = fileHelper.GetIDFile();
		
		// below, if we could find the stream, we'll set this true
		InterfacePtr<IPMStream> iDataFileStream(StreamUtil::CreateFileStreamReadLazy(xFile));
		// If nil, we couldn't have opened this
		if (iDataFileStream == nil)
		{
			////cout << "iDataFileStream is nil" << endl;
			break;
		}
		
		iDataFileStream->Close();
		
		InterfacePtr<ISysFileData> iSysFileData(iViewWidgetView, IID_ISYSFILEDATA);
		ASSERT(iSysFileData);
		if(!iSysFileData)
		{
			////cout << "iSysFileData is nil" << endl;  
			break;
		}
		// set display default preview image
		{
			iSysFileData->Set(xFile);
			iViewWidgetView->Invalidate();
		}

	} while(kFalse);
}


/********************************************************************************************************************
 *****Function: updatePackageSession
 *****Creator:  Toan Nguyen
 *****IN: 
 *****out: 
 *****Objective: update new session for pages
 ********************************************************************************************************************/
int AMPListBoxObserver::updatePackageSession()
{
	string _error_info;
	RangeProgressBar *Progress;
	Progress = new RangeProgressBar("Connecting to...", 0, 100, kTrue, kFalse, nil, kFalse);
	Progress->SetPosition(50);
	int returnCode = 0;
	////cout << "Reset time connection" << endl;
	//int32 totaltime = (n_mSessionCounterReset * 10);
	returnCode = HTTPRequestHelper::RequestSession();
	
	Progress->SetPosition(80);
	if(returnCode == -1)
	{
		_error_info = "Lost session working, this package will be invalid to use (user id - session - package): (" + g_Username + " - " + n_mSessionID + " - " + g_Package_id + ")";
		SaveLogCenterData(_error_info);
		AMPLogCenter::DataLogCenter(AMPPLUGIN_UPDATE_SESSION_FAILED);
		Progress->SetPosition(100);
		Progress->~RangeProgressBar();
		//This package will be invalid to use
		AMPCAlert::ModalAlert
		(
		 PMString("File open on another computer by same user.\n\nThis user session has now closed."),		// Alert string
		 PMString("Yes"),				// OK button
		 kNullString,					// Cancel button
		 kNullString, 					// No third button
		 kNoNeedToWaitForDialog,		// Set OK button to default
		 1								// No icon.
		 );
		// Clean up
		AMPUtils::CloseCurDocument();
		AMPUtils::ClearAllFile();
		AMPUtils::ClearPackageAndSessionInfo();
		AMPUtils::ClearUserInfo();
		AMPUtils::RefreshMainPanel(FALSE);
		
		return -1;
	}else if(returnCode == -2) {
		Progress->SetPosition(100);
		Progress->~RangeProgressBar();
		AMPCAlert::ModalAlert
		(
		 PMString("\n\nInternet connection lost. Retry check-in of the package?"),		// Alert string
		 PMString("Yes"),				// OK button
		 kNullString,					// Cancel button
		 kNullString, 					// No third button
		 kNoNeedToWaitForDialog,		// Set OK button to default
		 1								// No icon.
		 );
		
		return -1;
	}else {
		Progress->SetPosition(100);
		Progress->~RangeProgressBar();
		return 1;
	}
	Progress->SetPosition(100);
	Progress->~RangeProgressBar();
	return TRUE;
}

/********************************************************************************************************************
 *****Function: updateStorySession
 *****Creator:  Toan Nguyen
 *****IN: 
 *****out: 
 *****Objective: update new session for story
 ********************************************************************************************************************/
int AMPListBoxObserver::updateStorySession()
{
	RangeProgressBar *Progress;
	Progress = new RangeProgressBar("Connecting to...", 0, 100, kTrue, kFalse, nil, kFalse);
	Progress->SetPosition(30);
	int returnCode = 0;
	// request new session for stories
	for (int i = 0; i < g_TextFrameCount; i++) {
		if (g_TextFrames[i].isLocked == TRUE) {
			returnCode = HTTPRequestHelper::RequestStorySession(g_TextFrames[i].sessionID);
		}
	}
	Progress->SetPosition(80);
	if(returnCode == -1)
	{
		Progress->SetPosition(100);
		Progress->~RangeProgressBar();
		//This package will be invalid to use
		AMPCAlert::ModalAlert
		(
		 //PMString("Someone checked out current story on the other computer.\n\nThis story will be invalid to use."),		// Alert string
		 PMString("\n\nUnable to Check-in. Already in use by another user."),
		 PMString("Yes"),				// OK button
		 kNullString,					// Cancel button
		 kNullString, 					// No third button
		 kNoNeedToWaitForDialog,		// Set OK button to default
		 1								// No icon.
		 );
		/*
		// Clean up
		AMPUtils::ClearAllFile();
		AMPUtils::ClearPackageAndSessionInfo();
		AMPUtils::ClearUserInfo();
		AMPUtils::RefreshMainPanel(FALSE);
		 */
		
		return -1;
	}else if(returnCode == -2) {
		Progress->SetPosition(100);
		Progress->~RangeProgressBar();
		AMPCAlert::ModalAlert
		(
		 PMString("\n\nInternet connection lost. Retry check-in of the story?"),		// Alert string
		 PMString("Yes"),				// OK button
		 kNullString,					// Cancel button
		 kNullString, 					// No third button
		 kNoNeedToWaitForDialog,		// Set OK button to default
		 1								// No icon.
		 );
		
		return -1;
	}else {
		Progress->SetPosition(100);
		Progress->~RangeProgressBar();
		return 1;
	}
	Progress->SetPosition(100);
	Progress->~RangeProgressBar();
	return TRUE;
}